1 ========================================================================
2 CONSOLE APPLICATION : CSASPNETGridView Project Overview
3 ========================================================================
5 /////////////////////////////////////////////////////////////////////////////
8 This CSASPNETGridView project describes how to populate ASP.NET GridView
9 control and how to implement Insert, Edit, Update, Delete, Paging
10 and Sorting functions in ASP.NET GridView control.
12 This project includes two samples: DataInMemory and DataFromDatabase.
14 DataInMemory populates GridView with a simple DataTable. The DataTable
15 is stored in ViewState to persist data across postbacks.
17 DataFromDatabase populates GridView with data from SQL Server database in
18 ADO.NET way. The sample uses the GriView database.
20 /////////////////////////////////////////////////////////////////////////////
23 Step1. Create a C# ASP.NET Web Application named CSASPNETGridView in
24 Visual Studio 2010 / Visual Web Developer.
26 Step2. Drag a GridView control, a LinkButton control and a Panel control
27 into an ASP.NET Web Form page.
29 (1) Rename the controls as follows:
32 LinkButton1 -> lbtnAdd
35 (2) Change the Text property of lbtnAdd to AddNew.
37 (3) Right-click on gvPerson, select Show Smart Tag -> Auto Format,
38 choose style Oceanica and press OK to save.
40 (4) On Show Smart Tag, select Add New Columns, choose CommandField,
41 check Delete, Edit/Update and Show cancel button then press OK.
43 (5) On Show Smart Tag, select Add New Columns, choose BoundField,
44 and add the following three columns:
46 Header text Data field Read only
47 -----------------------------------------
53 (6) On Show Smart Tag, select Edit Columns,
54 un-check Auto-generate fields, select LastName field,
55 and click Convert this field into a TemplateField.
56 Do the same operation to FirstName field.
60 ASP.NET: Using TemplateFields in the GridView Control
61 MSDN: TemplateField Class
64 Step3. Copy the following methods from the sample,
65 and paste them in code-behind:
70 Initialize underlying objects, when the Page is accessed
73 InitializeDataSource Method:
74 Initialize the DataTable and store it in ViewState.
77 Set the sort column and sort order and bind the GridView
78 control with a DataTable in ViewState.
81 DataFromDatabase.aspx.cs
84 Initialize underlying objects, when the Page is accessed
88 Set the sort column and sort order and bind the GridView
89 control with a SQL Server table.
93 MSDN: using Statement (C# Reference)
94 MSDN: Understanding ASP.NET View State
97 Step4. Drag two TextBox controls and two LinkButton controls into
100 (1) Rename the controls as follows:
102 TextBox1 -> tbLastName
103 TextBox2 -> tbFirstName
104 LinkButton1 -> lbtnSubmit
105 LinkButton2 -> lbtnCancel
107 (2) Change the Text properties of lbtnSubmit and to Submit
110 Step5. Navigate to the Property panel of gvPerson and then switch to Event.
111 Double-click on the following events to generate the Event handlers.
112 After that, fill the generated methods with the sample code.
115 (1) RowDataBound Event: Occurs when a data row is bound to
116 data in a GridView control.
118 In this event, we add a client-side confirmation dialog box that
119 appears when the Delete button is clicked. It will prevent deleting a
124 MSDN: GridView.RowDataBound Event
125 ASP.NET: Editing, Inserting, and Deleting Data
126 ASP.NET: Adding Client-Side Confirmation When Deleting
127 MSDN: WebControl.Attributes Property
128 MSDN: DataControlRowType Enumeration
129 MSDN: GridViewRow.RowState Property
132 (2) PageIndexChanging Event: Occurs when one of the pager buttons is
133 clicked, but before the GridView control handles the paging operation.
135 In other to show data in the new page, we need to set the index of new
136 page and then rebind the GridView control to show data in view mode.
138 When clicking the Edit button to edit a particular row, the GridVew
139 control will enter the edit mode and show Update and Cancel buttons.
143 MSDN: GridView.PageIndexChanging Event
146 (3) RowEditing Event: Occurs when a row's Edit button is clicked,
147 but before the GridView control enters edit mode.
149 To make the GridView control into edit mode for the select row,
150 we need to set the index of the row to edit and then rebind the
151 GridView control to render data in edit mode.
155 MSDN: GridView.RowEditing Event
156 MSDN: GridView.EditIndex Property
159 (4) RowCancelingEdit Event: Occurs when the Cancel button of a row
160 in edit mode is clicked, but before the row exits edit mode.
162 We can click the Cancel button to cancel the edit mode and show data
165 In this Event, we need to set the zero-based GridView.EditIndex
166 property to -1, which means no row is being edited, and then rebind
167 the GridView to show data in view mode.
169 ////////////////////////////////////////////////////////////////
170 gvPerson.EditIndex = -1;
172 ////////////////////////////////////////////////////////////////
176 MSDN: GridView.RowCancelingEdit Event
179 (5) RowUpdating Event: Occurs when a row's Update button is clicked,
180 but before the GridView control updates the row.
182 After modifying values in the selected row, we click the Update button
183 to save changes back to the data source.
185 To identify the person for editing, the PersonID value is required,
186 which is read-only and cannot be modified.
188 ////////////////////////////////////////////////////////////////
189 string strPersonID = gvPerson.Rows[e.RowIndex].Cells[2].Text;
190 ////////////////////////////////////////////////////////////////
192 e.RowIndex is the index of current row.
194 In Step2 we converted LastName and FirstName to TemplateFields, so we
195 cannot get the edit values directly. Since LastName and FirstName are
196 both string values, Label controls are generated in ItemTemplate for
197 displaying values and TextBox controls are generated in EditItemTemplate
200 We can access the cells and fetch the values in the following way:
202 ////////////////////////////////////////////////////////////////
204 ((TextBox)gvPerson.Rows[e.RowIndex].FindControl("TextBox1")).Text;
206 string strFirstName =
207 ((TextBox)gvPerson.Rows[e.RowIndex].FindControl("TextBox2")).Text;
208 ////////////////////////////////////////////////////////////////
210 After fetch these values, we can save them back to the DataTable in
211 ViewState or the table in SQL Server.
215 MSDN: GridView.RowUpdating Event
216 ASP.NET: Editing, Inserting, and Deleting Data
219 (6) RowDeleting Event: Occurs when a row's Delete button is clicked,
220 but before the GridView control deletes the row.
222 To identify the person for deleting, the PersonID value is required,
223 which is read-only and cannot be modified.
225 ////////////////////////////////////////////////////////////////
226 string strPersonID = gvPerson.Rows[e.RowIndex].Cells[2].Text;
227 ////////////////////////////////////////////////////////////////
229 After fetching the PersonID, we can delete the person from the DataTable
230 in ViewState or the table in SQL Server.
234 MSDN: GridView.RowDeleting Event
235 ASP.NET: Editing, Inserting, and Deleting Data
238 (7) Sorting Event: Occurs when the hyperlink to sort a column is
239 clicked, but before the GridView control handles the sort operation.
241 The SortDirection property on the GridView is changed only when the
242 GridView is bound to a DataSource control using the DataSourceID
243 property. Otherwise, sort direction always return "Ascending" and
244 needs to be manipulated manually.
246 In the Page_Load Event, we store a default sorting expression
249 ////////////////////////////////////////////////////////////////
250 ViewState["SortExpression"] = "PersonID ASC";
251 ////////////////////////////////////////////////////////////////
253 And set the sort column and sort order based on it in BindGridView method.
255 ////////////////////////////////////////////////////////////////
256 dvPerson.Sort = ViewState["SortExpression"].ToString();
257 ////////////////////////////////////////////////////////////////
259 So when first visiting the page, all Person record will be shown in
260 ascending order of PersonID.
262 When clicking a column’s header to sort
263 this column, we need to get previous sort column and sort order and
264 compare the sort column with the current column.
266 If they are same, we just change the sort order to show data in the
267 other order, e.g. ascending to descending or descending to ascending.
269 If not, we specify the current column as the sort column and set sort
270 order to ASC. The sort expression is stored into ViewState to persist
271 data across postbacks.
275 MSDN: DataView.Sort Property
276 MSDN: GridView.Sorting Event
279 Step6. Double-click on the Click event of lbtnAdd to generate the Event
280 handlder and fill the generated methods with the sample code. Do the same
281 operations to lbtnSubmit and lbtnCancel.
284 Hide the Add button and showing Add panel.
286 lbtnSubmit.Click Event:
287 Fetch the values of the TextBox controls and add new row to the
288 DataTable in ViewState or the table in SQL Server.
290 lbtnCancel.Click Event:
291 Show the Add button and hiding the Add panel.
295 /////////////////////////////////////////////////////////////////////////////
298 MSDN: using Statement (C# Reference)
299 http://msdn.microsoft.com/en-us/library/yh598w02.aspx
301 MSDN: Understanding ASP.NET View State
302 http://msdn.microsoft.com/en-us/library/ms972976.aspx
304 ASP.NET: Using TemplateFields in the GridView Control
305 http://www.asp.net/learn/data-access/tutorial-12-cs.aspx
307 MSDN: TemplateField Class
308 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.templatefield.aspx
310 MSDN: GridView.RowDataBound Event
311 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound.aspx
313 ASP.NET: Editing, Inserting, and Deleting Data
314 http://www.asp.net/learn/data-access/#editinsertdelete
316 ASP.NET: Adding Client-Side Confirmation When Deleting
317 http://www.asp.net/learn/data-access/tutorial-22-cs.aspx
319 MSDN: WebControl.Attributes Property
320 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webcontrol.attributes.aspx
322 MSDN: DataControlRowType Enumeration
323 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datacontrolrowtype.aspx
325 MSDN: GridViewRow.RowState Property
326 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewrow.rowstate.aspx
328 MSDN: GridView.PageIndexChanging Event
329 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.pageindexchanging.aspx
331 MSDN: GridView.RowEditing Event
332 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowediting.aspx
334 MSDN: GridView.EditIndex Property
335 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.editindex.aspx
337 MSDN: GridView.RowCancelingEdit Event
338 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcancelingedit.aspx
340 MSDN: GridView.RowUpdating Event
341 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowupdating.aspx
343 MSDN: GridView.RowDeleting Event
344 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdeleting.aspx
346 MSDN: DataView.Sort Property
347 http://msdn.microsoft.com/en-us/library/system.data.dataview.sort.aspx
349 MSDN: GridView.Sorting Event
350 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx
352 /////////////////////////////////////////////////////////////////////////////